package com.huawo.qjs.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.util.Log;

import com.sifli.ezip.sifliEzipUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class QjsUtils {

    private static final String TAG = "QjsUtils";
    private static byte[] sourceBytes;
    private static byte[] bytes;

    /**
     * 获取qjs表盘本地存储目录（iOS可以使用cache或者document目录
     *
     * @param context android上下文，iOS没有
     * @return 目录
     */
    private static File getCacheDir(Context context) {
        // cacheDir = context.getCacheDir();
//        File cacheDir = context.getExternalFilesDir("watchfaces");
        File cacheDir = context.getCacheDir();
        if (cacheDir != null) {
            // 目录存在或已成功创建
            Log.d("ExternalFilesDir", "Directory path: " + cacheDir.getAbsolutePath());
        } else {
            // 目录创建失败
            Log.e("ExternalFilesDir", "Failed to create directory");
        }
        return cacheDir;
    }

    /**
     * 用来打包zip包的目录
     *
     * @param watchfaceName 表盘名称
     * @param context       android上下文
     * @return 目录
     */
    public static File qjsToZipFolder(String watchfaceName, Context context) {
        File dir = getCacheDir(context);
        return new File(dir, "qjs_temp/dyn");
    }

    public static String qjsOutputPath(String watchfaceName, Context context) {
        File dir = getCacheDir(context);
        File tempDir = new File(dir, "qjs_temp/output");
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
        return dir.getAbsolutePath() + "/qjs_temp/output/JW_" + watchfaceName + ".zip";
    }

    public static String jwPath(String watchfaceName) {
        return "qjs_temp/dyn/dynamic_app/qjs_wf/JW_" + watchfaceName;
    }

    public static String aodPath(String watchfaceName) {
        return "qjs_temp/dyn/dynamic_app/qjs_aod/AOD_" + watchfaceName;
    }

    public static String jwAbsolutePathD(String watchfaceName, Context context) {
        String jwTmpDir = "qjs_temp/dyn/dynamic_app/qjs_wf/JW_" + watchfaceName;
        File cacheDir = getCacheDir(context);
        return cacheDir.getAbsolutePath() + "/" + jwTmpDir;
    }

    public static String aodAbsolutePath(String watchfaceName, Context context) {
        String aodTmpDir = "qjs_temp/dyn/dynamic_app/qjs_aod/AOD_" + watchfaceName;
        File cacheDir = getCacheDir(context);
        return cacheDir.getAbsolutePath() + "/" + aodTmpDir;
    }

    public static boolean createQjsTmpDir(String watchfaceName, Context context) {
        // 创建完整了qjs表盘目录
        // dyn\dynamic_app\qjs_aod\AOD_name
        // dyn\dynamic_app\qjs_wf\JW_name
        String jwTmpDir = jwPath(watchfaceName);
        String aodTmpDir = aodPath(watchfaceName);
//        File cacheDir = context.getFilesDir();
        File cacheDir = getCacheDir(context);

        File tempDir1 = new File(cacheDir, jwTmpDir);
        deleteDirectory(tempDir1);
        File tempDir2 = new File(cacheDir, aodTmpDir);
        deleteDirectory(tempDir2);
        if (!tempDir1.mkdirs()) {
            Log.e(TAG, "createQjsTmpDir: 失败|" + tempDir1.getAbsolutePath());
            return false;
        }
        if (!tempDir2.mkdirs()) {
            Log.e(TAG, "createQjsTmpDir: 失败|" + tempDir2.getAbsolutePath());
            return false;
        }

        Log.i(TAG, "createQjsTmpDir: " + tempDir2.getAbsolutePath());

        return true;
    }

    private static void deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        // 递归删除子目录
                        deleteDirectory(file);
                    } else {
                        // 删除文件
                        if (!file.delete()) {
                            Log.e(TAG, "deleteDirectory: 删除文件失败|" + file.getAbsolutePath());
                        }
                    }
                }
            }
            // 删除空目录
            // directory.deleteOnExit();
        }
    }

    public static void exportBin(Bitmap source, int color, boolean isAOD, boolean isTimeHand, String fileName, String watchfaceName, Context context) {
        // 如果颜色不是白色，则需要转成其他颜色
        if (color != 0xFFFFFF) {
            source = changeBitmapColor(source, color);
        }

        byte[] sourceBytes = bitmapToByteArray(source);
        Log.i(TAG, "exportBin: start, file size:" + sourceBytes.length);
//        Log.i(TAG, "exportBin: start, file content:" + byteArrayToHexString(sourceBytes));
        byte[] bytes = sifliEzipUtil.pngToEzip(sourceBytes, "rgb565a", 0, isTimeHand ? 0 : 1, 1);

        Log.i(TAG, "exportBin: end");

        writeByteArray(bytes, fileName, isAOD, watchfaceName, context);
    }
//    /**
//     * 二进制数组转十六进制字符串
//     *
//     * @param bytes byte array to be converted
//     * @return string containing hex values
//     */
//    public static String byteArrayToHexString(byte[] bytes) {
//        StringBuilder sb = new StringBuilder(bytes.length * 2);
//        for (byte element : bytes) {
//            int v = element & 0xff;
//            if (v < 16) {
//                sb.append('0');
//            }
//            sb.append(Integer.toHexString(v));
//        }
//        return sb.toString().toUpperCase(Locale.US);
//    }


    /**
     * GIF byte写入压缩包
     */
    public static void exportBin(byte[] source, int color, boolean isAOD, boolean isTimeHand, String fileName, String watchfaceName, Context context) {

        int binType = isTimeHand ? 0 : 1;

        if (source.length == 0) {
            return;
        }
        byte[] bytesNew = sifliEzipUtil.pngToEzip(source, "rgb565a", 0, binType, 1);

        writeByteArray(bytesNew, fileName, false, watchfaceName, context);

    }

    public static void writeMainJS(String content, boolean isAOD, String watchfaceName, Context context) {
        String path = isAOD ? aodAbsolutePath(watchfaceName, context) : jwAbsolutePathD(watchfaceName, context);
//        path = path + "/main.js";
        path = path + (isAOD ? "/AOD_" + watchfaceName + "_main.js" : "/JW_" + watchfaceName + "_main.js");
        Log.i(TAG, "writeMainJS: " + path);
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
            // bytes = addCrc2Bytes("main.js", bytes);
            os.write(bytes);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            Log.e(TAG, "writeMainJS: " + e.getLocalizedMessage());
        }
    }

    public static String packageQjs(String watchfaceName, Context context) {
        String zipPath = qjsOutputPath(watchfaceName, context);
        File folder = qjsToZipFolder(watchfaceName, context);
        try {
            FileOutputStream fos = new FileOutputStream(zipPath);
            ZipOutputStream zos = new ZipOutputStream(fos);
            addFolderToZip(folder, folder.getName(), zos);
            zos.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            zipPath = null;
        }
        return zipPath;
    }

    private static void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos) throws Exception {
        File[] files = folder.listFiles();
        byte[] buffer = new byte[1024];
        int len;

        for (File file : files) {
            if (file.isDirectory()) {
                addFolderToZip(file, parentFolder + "/" + file.getName(), zos);
                continue;
            }

            FileInputStream fis = new FileInputStream(file);
            zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName()));

            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            zos.closeEntry();
            fis.close();
        }
    }

    public static Bitmap changeBitmapColor(Bitmap originalBitmap, int color) {
        // 创建一个新的图片，与原始图片尺寸相同
        Bitmap coloredBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        // 创建一个画布，并将新的图片与之关联
        Canvas canvas = new Canvas(coloredBitmap);
        // 获取颜色的RGB分量
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);

        // 应用颜色矩阵来改变图片颜色
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.set(new float[]{
                red / 255f, 0, 0, 0, 0, // 红色分量
                0, green / 255f, 0, 0, 0, // 绿色分量
                0, 0, blue / 255f, 0, 0, // 蓝色分量
                0, 0, 0, 1, 0 // 透明度
        });
        // 创建颜色滤镜
        ColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
        // 在画布上绘制原始图片，并应用颜色滤镜
        Paint paint = new Paint();
        paint.setColorFilter(colorFilter);
        canvas.drawBitmap(originalBitmap, 0, 0, paint);
        return coloredBitmap;
    }

    public static void writeByteArray(byte[] bytes, String fileName, boolean isAOD, String watchfaceName, Context context) {
        String path = isAOD ? aodAbsolutePath(watchfaceName, context) : jwAbsolutePathD(watchfaceName, context);
        String namePrefix = isAOD ? ("AOD_" + watchfaceName + "_") : ("JW_" + watchfaceName + "_");
        path = path + "/" + namePrefix + fileName;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            fos.write(bytes);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public static boolean copyFile(String oldPathName, String newPathName) {
        try {
            File oldFile = new File(oldPathName);
            if (!oldFile.exists()) {
                Log.e("copyFile", "copyFile:  oldFile not exist.");
                return false;
            } else if (!oldFile.isFile()) {
                Log.e("copyFile", "copyFile:  oldFile not file.");
                return false;
            } else if (!oldFile.canRead()) {
                Log.e("copyFile", "copyFile:  oldFile cannot read.");
                return false;
            }
            FileInputStream fileInputStream = new FileInputStream(oldPathName);
            FileOutputStream fileOutputStream = new FileOutputStream(newPathName);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * PNG Bitmap转成二进制数组
     *
     * @param bitmap
     * @return
     */
    public static byte[] bitmapToByteArray(Bitmap bitmap) {
        /**
         * demo:
         * Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_image);
         * byte[] byteArray = convertBitmapToByteArray(bitmap);
         */
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 20, stream);
        return stream.toByteArray();
    }

    public static byte[] bytesFromAsset(String name, Context context) {
        byte[] bytes = new byte[0];
        try {
            AssetManager assetManager = context.getAssets();
            InputStream inputStream = assetManager.open("file.txt");

            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteStream.write(buffer, 0, bytesRead);
            }
            bytes = byteStream.toByteArray();
            byteStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    /**
     * 获取二进制数据的crc值
     *
     * @param pSrc
     * @return
     */
    public static int getCrc(byte[] pSrc) {
        int crc = 0xffffffff;
        for (int m = 0; m < pSrc.length; m++) {
            crc ^= ((int) pSrc[m]) << 24;
            for (int n = 0; n < 8; n++) {
                if ((crc & 0x80000000) != 0) {
                    crc = (crc << 1) ^ 0x04c11db7;
                } else {
                    crc <<= 1;
                }
            }
        }
        return crc;
    }

    /**
     * 给文件尾部添加crc值
     *
     * @param fileName
     * @param bytes
     * @return
     */
    public static byte[] addCrc2Bytes(String fileName, byte[] bytes) {
        if (bytes == null) {
            return new byte[0];
        }
        byte[] result = bytes;

        int length = bytes.length;
        int reminder = length % 4;
        if (reminder > 0) {
            int paddingLen = 4 - reminder;
            result = new byte[length + paddingLen];
            // Copy the original array to the padded array
            System.arraycopy(bytes, 0, result, 0, length);

            byte toPaddingByte = 0;
            if (fileName.toLowerCase().endsWith(".js")) {
                toPaddingByte = 0x20;
            }

            // Fill the padding bytes with toPaddingByte
            for (int i = length; i < length + paddingLen; i++) {
                result[i] = toPaddingByte;
            }
        }

        int crc = getCrc(result);
        ByteBuffer crcBuffer = ByteBuffer.allocate(4);  // 创建一个4字节的ByteBuffer
        crcBuffer.order(ByteOrder.LITTLE_ENDIAN);  // 设置字节顺序为小端序
        crcBuffer.putInt(crc);

        crcBuffer.flip();  // 切换为读模式
        byte[] crcBytes = new byte[crcBuffer.remaining()];  // 创建一个与ByteBuffer剩余字节大小相同的字节数组
        crcBuffer.get(crcBytes);

        StringBuilder sb = new StringBuilder();
        for (int i = crcBytes.length - 1; i >= 0; i--) {
            byte b = crcBytes[i];
            sb.append(String.format(Locale.ENGLISH, "%02X", b)); // 将每个字节转换为16进制字符串形式，并追加到StringBuilder中
        }
        Log.i(TAG, fileName + "|crc: " + sb);

        byte[] finalBytes = new byte[result.length + 4];
        System.arraycopy(result, 0, finalBytes, 0, length);
        System.arraycopy(crcBytes, 0, finalBytes, result.length, 4);

        return finalBytes;
    }

    public static byte[] convertFileToByteArray(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        fis.read(buffer);
        fis.close();

        return buffer;
    }


    /**
     * 相册功能，图片转bin文件
     * PNG_fileName.bin //目标文件名
     */
    public static String exportBin(byte[] source, String fileName, Context context) {
        String path = "";
        Log.e(TAG, "source.length==" + source.length);
        if (source.length == 0) {
            Log.e(TAG, "source==0");
            return path;
        }
        byte[] bytesNew = sifliEzipUtil.pngToEzip(source, "rgb565a", 0, 1, 1);
        Log.e(TAG, "bytesNew==" + bytesNew.length);
//        PNG_fileName.bin
//        String path = isAOD ? aodAbsolutePath(watchfaceName, context) : jwAbsolutePathD(watchfaceName, context);
//        String namePrefix = isAOD ? ("AOD_" + watchfaceName + "_") : ("JW_" + watchfaceName + "_");
//        //文件夹+路径
        String folderPath = getCacheDir(context) + "/photo";
        File folder = new File(folderPath);
//
        if (!folder.exists()) {
            boolean folderCreated = folder.mkdir(); // 尝试创建文件夹
            if (folderCreated) {
                Log.e(TAG, "文件夹已创建成功");
            } else {
                Log.e(TAG, "无法创建文件夹");
            }
        }

        path = getCacheDir(context) + "/photo/" + fileName;
        Log.e(TAG, "path==" + path);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            fos.write(bytesNew);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return path;

    }

    public static String allChangeToBin(Context context, List<String> filePaths, int width, int height, List<Integer> idList) {
        Log.e(TAG, "come in === allChangeToBin==");
        ArrayList<String> list = new ArrayList<>();
        try {
            int size = filePaths.size();
            for (int i = 0; i < size; i++) {
                try {
                    int firmwareID = i + 1;
                    Bitmap bitmap = cropAndScaleImage(filePaths.get(i), width, height);
//                Bitmap bitmap = BitmapFactory.decodeFile(filePaths.get(i));
                    byte[] sourceBytes = bitmapToByteArray(bitmap);
//                    String fileName = splitFileName(filePaths.get(i));
                    String resultPath = exportBin(sourceBytes, "PNG_" + idList.get(i) + ".bin", context);
                    list.add(resultPath);
                    //缩略图
                    Bitmap bitmapPre = cropAndScaleImage(filePaths.get(i), width / 3, height / 3);
                    byte[] sourceBytesPre = bitmapToByteArray(bitmapPre);
//                    String fileNamePre = splitFileName(filePaths.get(i));
                    String resultPathPre = exportBin(sourceBytesPre, "PRE_" + idList.get(i) + ".bin", context);
                    Log.e(TAG, "=== allChangeToBin== resultPathPre===" + resultPathPre + "= resultPath===" + resultPath);
                    list.add(resultPathPre);
                } catch (Exception exception) {

                }

            }
            return compressFilesToZip(context, list);
        } catch (Exception e) {
            Log.e(TAG, "allChangeToBin==IOException");
        }
        return "";
    }

    public static String compressFilesToZip(Context context, List<String> filePaths) {
        String targetZipPath = getCacheDir(context) + "/photo/target.zip";
        Log.e(TAG, "targetZipPath==targetZipPath==" + targetZipPath);
        try {
            FileOutputStream fos = new FileOutputStream(targetZipPath);
            ZipOutputStream zos = new ZipOutputStream(fos);

            for (String filePath : filePaths) {
                File file = new File(filePath);
                if (file.exists()) {
                    if (file.isFile()) {
                        zipFile(file, zos);
                    } else if (file.isDirectory()) {
                        zipDirectory(file, zos, "");
                    }
                } else {
                    Log.e(TAG, "File does not exist: " + filePath);
                }
            }

            zos.close();
            fos.close();

            Log.e(TAG, "Files compressed to: " + targetZipPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return targetZipPath;
    }


    public static Bitmap cropAndScaleImage(String filePath, int width, int height) {
        Bitmap resultBitmap = null;

        Matrix matrix = new Matrix();

        // 读取图片的EXIF数据以获取旋转角度
        int rotation = getExifRotation(filePath);
        if (rotation != 0) {
            matrix.postRotate(rotation);
        } else {
            Log.e(TAG, "Files rotation==0");
        }

        // 加载图片并获取原始大小
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int imageWidth = options.outWidth;
        int imageHeight = options.outHeight;

        float scaleWidth = (float) width / imageWidth;
        float scaleHeight = (float) height / imageHeight;
        // 计算缩放比例
        float scaleFactor = Math.max(scaleWidth, scaleHeight);
//        float scaleFactor = ((float) height) / imageHeight;

        // 设置缩放和旋转矩阵
//        Matrix matrix = new Matrix();
        matrix.postScale(scaleFactor, scaleFactor);

        // 加载原图并按照计算后的比例进行缩放
        options.inJustDecodeBounds = false;
        Bitmap sourceBitmap = BitmapFactory.decodeFile(filePath, options);
        resultBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, imageWidth, imageHeight, matrix, true);

        // 裁剪中心部分
        int x = (resultBitmap.getWidth() - width) / 2;
        int y = (resultBitmap.getHeight() - height) / 2;
        if (x < 0) {
            x = 0;
        }
        if (y < 0) {
            y = 0;
        }
        resultBitmap = Bitmap.createBitmap(resultBitmap, x, y, width, height);

        return resultBitmap;
    }
//
//    public static Bitmap cropAndScaleImage(String filePath, int width, int height) {
//        Bitmap resultBitmap = null;
//        Matrix matrix = new Matrix();
//
//        // 读取图片的EXIF数据以获取旋转角度
//        int rotation = getExifRotation(filePath);
//        if (rotation != 0) {
//            matrix.postRotate(rotation);
//        }else{
//            Log.e(TAG, "Files rotation==0");
//        }
//
//        // 加载图片并获取原始大小
//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inJustDecodeBounds = true;
//        BitmapFactory.decodeFile(filePath, options);
//        int imageWidth = options.outWidth;
//        int imageHeight = options.outHeight;
//
//        // 计算缩放比例
//        float scaleFactor = Math.min((float) width / imageWidth, (float) height / imageHeight);
//
//        // 设置缩放矩阵
//        matrix.postScale(scaleFactor, scaleFactor);
//
//        // 更新options以加载缩放后的图片
//        options.inJustDecodeBounds = false;
//        options.inSampleSize = (int) scaleFactor;
//        Bitmap sourceBitmap = BitmapFactory.decodeFile(filePath, options);
//
//        // 应用旋转和缩放
//        resultBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, imageWidth, imageHeight, matrix, true);
//        sourceBitmap.recycle(); // 回收原始Bitmap以节省内存
//
//        // 裁剪中心部分
//        int x = (int) Math.max((resultBitmap.getWidth() - width) / 2, 0);
//        int y = (int) Math.max((resultBitmap.getHeight() - height) / 2, 0);
//        resultBitmap = Bitmap.createBitmap(resultBitmap, x, y, width, height);
//
//        return resultBitmap;
//    }

    private static int getExifRotation(String filePath) {
        int rotation = 0;
        try {
            ExifInterface exif = new ExifInterface(filePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotation = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotation = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotation = 270;
                    break;
                default:
                    rotation = 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rotation;
    }

    public static Bitmap cropAndScaleImage1(String filePath, int width, int height) {
        Bitmap resultBitmap = null;

        // 加载图片并获取原始大小
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int imageWidth = options.outWidth;
        int imageHeight = options.outHeight;
//
        // 读取图片的Exif信息，以判断是否需要旋转
        int rotation = 0;
        try {
            ExifInterface exif = new ExifInterface(filePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotation = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotation = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotation = 270;
                    break;
                default:
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

//        // 根据旋转角度调整宽高
        Matrix matrix = new Matrix();
        Log.d("QJSUTIL", "rotation==" + rotation);
        if (rotation != 0) {
            matrix.postRotate(rotation);
            // 交换宽度和高度，因为图片已经旋转
            int temp = imageWidth;
            imageWidth = imageHeight;
            imageHeight = temp;
        }

        // 计算缩放比例
//        float scaleFactor = Math.min(((float) width / imageWidth), ((float) height / imageHeight));

        // 加载原图并按照计算后的比例进行缩放
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateInSampleSize(options, width, height);
        Bitmap sourceBitmap = BitmapFactory.decodeFile(filePath, options);

        // 应用缩放和旋转
        resultBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, true);

        // 根据缩放后的宽高进行裁剪
        int cropWidth = resultBitmap.getWidth();
        int cropHeight = resultBitmap.getHeight();
        if (cropWidth > width || cropHeight > height) {
            int x = (cropWidth - width) / 2;
            int y = (cropHeight - height) / 2;
            resultBitmap = Bitmap.createBitmap(resultBitmap, x, y, width, height);
        }

        return resultBitmap;
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // 计算最大的inSampleSize值，这是一个2的幂，并且是保持图片大小在请求大小之上的最大值
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    private static void zipFile(File file, ZipOutputStream zos) throws IOException {
        FileInputStream fis = new FileInputStream(file);

        String zipFilePath = "music/photo" + "/" + file.getName();

        ZipEntry zipEntry = new ZipEntry(zipFilePath);
        zos.putNextEntry(zipEntry);

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            zos.write(buffer, 0, bytesRead);
        }

        fis.close();
        zos.closeEntry();
    }

    private static void zipDirectory(File directory, ZipOutputStream zos, String parentPath) throws IOException {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    zipFile(file, zos);
                } else if (file.isDirectory()) {
                    String directoryPath = parentPath + file.getName() + "/";
                    zipDirectory(file, zos, directoryPath);
                }
            }
        }
    }

    public static String splitFileName(String filePath) {
        String fileName = new File(filePath).getName();
        String[] parts = fileName.split("\\."); // 以.为分隔符分割文件名
        if (parts.length > 1) {
            Log.e(TAG, "文件名的特定部分: " + parts[0]);
            return parts[0]; // 获取没有扩展名的部分
        } else {
            long currentTimestamp = System.currentTimeMillis();
            Log.e(TAG, "无法提取文件名的特定部分");
            return "IMG_" + currentTimestamp;
        }
    }

    public static void clearDirectory(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                File temp = new File(dir, children[i]);
                if (temp.isDirectory()) {
                    clearDirectory(temp);
                } else {
                    temp.delete();
                }
            }
        } else if (dir != null && dir.isFile()) {
            dir.delete(); // 如果 dir 直接是一个文件，则删除它
        }
    }
}
